package com.ztf.satoken.test;

import cn.dev33.satoken.httpauth.basic.SaHttpBasicUtil;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/")
public class UserController {

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public String doLogin(String username, String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对 
        if("zhang".equals(username) && "123456".equals(password)) {
            StpUtil.login(10001);
            return "登录成功";
        }
        return "登录失败";
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @RequestMapping("/getSession")
    public Map<String, Object> getSession() {
        SaSession currentAccountSession = StpUtil.getSession();
        SaSession accountSession = StpUtil.getSessionByLoginId(10001);
        SaSession tokenSession = StpUtil.getTokenSession();
        System.out.println(currentAccountSession);
        System.out.println(accountSession);
        System.out.println(tokenSession);
        Map<String, Object> map = new HashMap<>();
        map.put("currentAccountSession", currentAccountSession);
        map.put("accountSession", accountSession);
        map.put("tokenSession", tokenSession);
        map.put("device", StpUtil.getLoginDeviceType());
        return map;
    }

    @RequestMapping("test3")
    public SaResult test3() {
        SaHttpBasicUtil.check("sa:123456");
        // ... 其它代码
        return SaResult.ok();
    }
}